//
//  SinaComposeViewController.swift
//  SinaWeibo
//
//  Created by 王朝阳 on 2016/11/4.
//  Copyright © 2016年 wangzhaoyang. All rights reserved.
//

import UIKit
import SVProgressHUD

@available(iOS 9.0, *)
class SinaComposeViewController: UIViewController {
    
    //MARK: - 懒加载控件
    fileprivate lazy var titleLabel: UILabel = {
       
        let lab = UILabel()
        lab .textColor = UIColor.darkGray
        lab.font = UIFont.systemFont(ofSize: 17)
        lab.textAlignment = .center
        lab.numberOfLines = 0
        
        //判断用户的昵称是否为nil
        if let name = SinaUserAccountViewModel.sharedTools.userAccountModel?.screen_name {
            let title = "发微博\n" + name
            //创建富文本
            let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: title)
            //获取 name 的 rang
            let rang = (title as NSString).range(of: name)
            attributedString.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: UIColor.red], range: rang)
            lab.attributedText = attributedString
        }else {
            lab.text = "发微博"
        }
        lab.sizeToFit()
        return lab
        
    }()

    //发送按钮
    fileprivate lazy var sendButton: UIButton = {
        let button = UIButton()
        
        button.addTarget(self, action: #selector(sendActionClick), for: .touchUpInside)
        //设置按钮不同状态下的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        //设置文字颜色
        button.setTitle("发送", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        //设置字体大小
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        button.size = CGSize(width: 45, height: 35)
        return button
    }()
    
    //textView输入框
    fileprivate lazy var textView: UITextView = {
       let composeTextView = SinaComposeTextView()
        composeTextView.placeHolder = "别怕我来了!!!"
        composeTextView.font = UIFont.systemFont(ofSize: 14)
        //设置代理
        composeTextView.delegate = self
        
        //让 textView 能都拖动
        composeTextView.alwaysBounceHorizontal = true
        return composeTextView
    }()
    
    //toolBar
    fileprivate lazy var toolBar: SinaComposeToolBar = {
        let composeToolBar = SinaComposeToolBar()
        return composeToolBar
    }()
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        setupUI()
    }
    private func setupUI() {
        setupNav()
        view.addSubview(textView)
        
        view.addSubview(toolBar)
       
        textView.snp_makeConstraints { (make) in
            make.top.leading.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        toolBar.snp_makeConstraints { (make) in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(35)
        }
        
        //键盘 frame 的改变
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    //设置导航栏视图操作
    private func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target:  self, action: #selector(cancelAction))
        
        //设置顶部视图
        navigationItem.titleView = titleLabel
        
        //发送按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    //MARK: - 取消按钮
    @objc func cancelAction() {
        //让当前 view 结束编辑状态也可以让键盘失去第一响应
        self.view.endEditing(true)
        
        dismiss(animated: true, completion: nil)
    }
    //发送微博
    @objc func sendActionClick() {
        let accessToken = SinaUserAccountViewModel.sharedTools.accessToken!
        //获取微博内容
        let status = textView.text!
        SVProgressHUD.show()
        HMNetworkTools.sharedTools.update(access_token: accessToken, status: status, success: { (reponse) in
            SVProgressHUD.showSuccess(withStatus: "发送成功")
        }) { (error) in
            print(error)
            SVProgressHUD.showError(withStatus: "发送失败")
        }
    }
    
    //MARK: - 监听键盘 frame 的改变
    @objc private func keyboardFrameChange(noti: Notification) {
        //获取键盘的 frame
        let keybardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        //动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //更新底部约束
        toolBar.snp_updateConstraints { (make) in
            //键盘的 y - 屏幕的高,就是 toolBar 距离 view 底部的距离
            make.bottom.equalTo(view).offset(keybardFrame.origin.y - SinaScreenH)
        }
        
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    deinit {
        //移除通知
        NotificationCenter.default.removeObserver(self)
    }
}
//MARK: - 代理方法UITextViewDelegate
@available(iOS 9.0, *)
extension SinaComposeViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        //判断 textView是否有内容,如果有让按钮可以点击
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //让键盘失去第一响应
        self.view.endEditing(true)
    }
}
